package com.lucky.controller;

import com.alibaba.fastjson.JSON;
import com.lucky.annotation.Authority;
import com.lucky.pojo.vo.User;
import com.lucky.service.UserService;
import com.lucky.util.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author Jalyson
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/6/26
 */
@Controller
public class LoginController {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "index";
    }

    @PostMapping("/login")
    public ModelAndView login(User user, HttpServletRequest request) {
        User authUser = userService.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (authUser != null) {
            LOGGER.info("成功登录用户：{}", JSON.toJSONString(authUser));
            authUser.setToken(request.getSession().getId());
            RedisCache.cacheData(authUser.getToken(), authUser);
            ModelAndView model = new ModelAndView("redirect:/home");
            return model;
        }
        ModelAndView model = new ModelAndView("index");
        model.addObject("error", "login error.");
        return model;
    }

    @Authority(permission = false)
    @PostMapping("/login2")
    @ResponseBody
    public User login2(User user, HttpServletRequest request) {
        User authUser = userService.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (authUser != null) {
            LOGGER.info("成功登录用户：{}", JSON.toJSONString(authUser));
            authUser.setToken(request.getSession().getId());
            RedisCache.cacheData(authUser.getToken(), authUser);
            return authUser;
        }
        return null;
    }

    @Authority(permission = false)
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request) {
        String id = request.getSession().getId();
        RedisCache.remove(id);
        request.getSession().invalidate();
        ModelAndView model = new ModelAndView("index");
        model.addObject("info", "退出成功");
        return model;
    }

}
